package com.github.editor.util;

import com.google.common.primitives.Bytes;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class MD5Util {
    @Nullable
    public static byte[] md5String8(String input) {
        byte[] bytes;
        try {
            bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return Arrays.copyOfRange(bytes, 4, 12);
    }

    @Nullable
    public static byte[] md5String16(String input) {
        byte[] bytes;
        try {
            bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return bytes;
    }

    @Nullable
    public static String md5String(String input) {
        byte[] bytes;
        try {
            bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return Bytes.toHexString(bytes);
    }

    @Nullable
    public static String md5StringHalf(String input) {
        byte[] bytes;
        try {
            bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return Bytes.toHexString(Arrays.copyOfRange(bytes, 4, 12));
    }

    @Nullable
    public static String md5File(String input) {
        return md5(new File(input));
    }

    @Nullable
    public static String md5(File file) {
        if (!file.isFile()) {
            return null;
        }
        try (FileInputStream in = new FileInputStream(file)) {
            return md5(in);
        } catch (Exception e) {
            return "00000000000000000000000000000000";
        }
    }

    @Nullable
    public static String md5(byte[] bs) throws NoSuchAlgorithmException {
        if (bs == null) {
            return null;
        }
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(bs, 0, bs.length);
        return Bytes.toHexString(digest.digest());
    }

    public static String md5(InputStream inputStream) throws NoSuchAlgorithmException, IOException {
        byte[] buffer = new byte[1024 * 4];
        int len;
        MessageDigest digest = MessageDigest.getInstance("MD5");
        while ((len = inputStream.read(buffer)) != -1) {
            digest.update(buffer, 0, len);
        }
        return Bytes.toHexString(digest.digest());
    }
}
